﻿using Jil;
using Newtonsoft.Json;
using System.Text;
namespace Athena.Codec.Implementations
{
    using Message;

    /// <summary>
    /// Json格式解码器
    /// 默认使用Jil
    /// 支持Newtonsoft.Json
    /// </summary>
    public class JsonRpcMessageDecoder : IRpcMessageDecoder
    {
        private Jil.Options _jilOptions = new Jil.Options(includeInherited: true);

        public RpcTransportMessage MessageDecoding(byte[] message)
        {
            var messageJsonString = Encoding.UTF8.GetString(message);
            return MessageDecoding(messageJsonString);
        }

        public RpcTransportMessage MessageDecoding(string message)
        {
            return JilJsonDecoding(message);
        }

        /// <summary>
        /// Newtonsoft解码
        /// </summary>
        /// <param name="message"></param>
        /// <returns></returns>
        private RpcTransportMessage NewtonsoftJsonDecoding(string message)
        {
            var rpcTransportMessage = JsonConvert.DeserializeObject<RpcTransportMessage>(message);
            if (rpcTransportMessage.IsInvokeMessage)
            {
                rpcTransportMessage.Content = JsonConvert.DeserializeObject<RpcInvokeMessage>(rpcTransportMessage.Content.ToString());
            }
            if (rpcTransportMessage.IsInvokeResultMessage)
            {
                rpcTransportMessage.Content = JsonConvert.DeserializeObject<RpcInvokeResultMessage>(rpcTransportMessage.Content.ToString());
            }
            return rpcTransportMessage;
        }

        /// <summary>
        /// Jil解码
        /// </summary>
        /// <param name="message"></param>
        /// <returns></returns>
        private RpcTransportMessage JilJsonDecoding(string message)
        {
            var rpcTransportMessage = JSON.Deserialize<RpcTransportMessage>(message);
            if (rpcTransportMessage.IsInvokeMessage)
            {
                rpcTransportMessage.Content = JSON.Deserialize<RpcInvokeMessage>(rpcTransportMessage.Content.ToString());
            }
            if (rpcTransportMessage.IsInvokeResultMessage)
            {
                rpcTransportMessage.Content = JSON.Deserialize<RpcInvokeResultMessage>(rpcTransportMessage.Content.ToString());
            }
            return rpcTransportMessage;
        }
    }
}
